package net.dubboclub.http.netty;


import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by bieber on 16/3/8.
 */
public class IdleTask implements Runnable {

    private ConcurrentHashMap<Channel, ChannelHolder> holderMapping;

    private long timeout;

    public IdleTask(long timeout, ConcurrentHashMap<Channel, ChannelHolder> holderMapping) {
        this.timeout = timeout;
        this.holderMapping = holderMapping;
    }

    @Override
    public void run() {
        Collection<ChannelHolder> channelHolderCollection = holderMapping.values();
        for (ChannelHolder channelHolder : channelHolderCollection) {
            long lastReadInterval =System.currentTimeMillis()-channelHolder.lastReadTime();
            long lastWriteInterval = System.currentTimeMillis()-channelHolder.lastWriteTime();
            if(lastReadInterval>=timeout&&lastWriteInterval>=timeout){
                channelHolder.channel().close().addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        holderMapping.remove(future.channel());
                    }
                });
            }
        }
    }


}
